import storage from '@/utils/storage';
import Vue from 'vue';
import Vuex from 'vuex';
import userApi from '../api/user'

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: storage.getToken() ? storage.getToken() : '',
    userInfo: storage.getUserInfo() ? storage.getUserInfo() : '',
  },
  mutations: {
    saveToken(state, token) {
      state.token = token;
      storage.setToken(token)
    },
    saveUserInfo(state, userInfo) {
      state.userInfo = userInfo;
      storage.setUserInfo(userInfo)
    },
  },
  actions: {
    doLogin({ commit }, ruleForm) {
      return new Promise((resolve, reject) => {
        userApi.doLogin(ruleForm.username, ruleForm.password).then(res => {
          if (res.data.flag) {
            commit('saveToken', res.data.data.token)
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getUserInfo({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        userApi.getUserInfo().then(res => {
          if (res.data.flag) {
            commit('saveUserInfo', res.data.data)
          }
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    getOut({ commit }) {
      return new Promise(async (resolve, reject) => {
        let res = await userApi.getOut()
        if (res.data.flag) {
          commit('saveToken', null)
          commit('saveUserInfo', null)
          storage.removeTokenAndUserInfo();
        }
        resolve(res)
      })
    }
  },
  modules: {

  },
});
